package com.fc.mall.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.fc.mall.model.UmsMember;
import com.fc.mall.model.UmsMemberForm;
import com.fc.mall.portal.connector.WeChatConnector;
import com.fc.mall.portal.service.MemberFormService;
import com.fc.mall.portal.service.RedisService;
import com.fc.mall.portal.service.SmsService;
import com.fc.mall.portal.service.UmsMemberService;
import com.fc.mall.portal.wechat.dto.WeappTemplate;
import com.fc.mall.portal.wechat.dto.WxsmallTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Sunny on 2019/7/18.
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Value("${aliyun.sms.domain}")
    private String DOMAIN;

    @Value("${aliyun.sms.version}")
    private String VERSION;

    @Value("${aliyun.sms.signName}")
    private String SIGNNAME;

    @Value("${aliyun.sms.templateCode}")
    private String TEMPLATECODE;

    @Value("${weapp.template.createOrderId}")
    private String CREATE_ORDER_TEMPLATE_ID;

    @Value("${weapp.template.deliveryOrderId}")
    private String DELIVERY_ORDER_TEMPLATE_ID;

    @Value("${weapp.template.incomeId}")
    private String INCOME_TEMPLATE_ID;

    @Value("${weapp.template.approval}")
    private String APPROVAL_TEMPLATE_ID;

    @Value("${weapp.template.withdraw}")
    private String WITHDRAW_TEMPATE_ID;

    @Value("${weapp.template.transferFail}")
    private String TRANSFER_FAILE_TEMPLATE_ID;


    @Value("${weapp.template.groupPurchaceId}")
    private String GROUP_PURCHASE_TEMPLATE_ID;

    @Value("${weapp.template.bargainInprogessId}")
    private String BARGAIN_INPROGESS_TEMPLATE_ID;

    @Value("${weapp.template.groupPurchaseFailId}")
    private String GROUP_PURCHASE_FAIL_TEMPLATE_ID;

    private final static String SEND_SMS_ACTION = "SendSms";

    @Autowired
    private IAcsClient iAcsClient;

    @Autowired
    private WeChatConnector weChatConnector;

    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private MemberFormService memberFormService;

    @Autowired
    private RedisService redisService;

    @Override
    public String sendSms(String phone) {
        String verifyCode = generate4Code()+"";
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(SEND_SMS_ACTION);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", SIGNNAME);
        request.putQueryParameter("TemplateCode", TEMPLATECODE);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", verifyCode);
        request.putQueryParameter("TemplateParam", jsonObject.toString());
        try {
            CommonResponse response = iAcsClient.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        redisService.set(phone, verifyCode);
        redisService.expire(phone, 5*60);
        return verifyCode;
    }

    @Override
    public void sendCreateOrderNotice(Long memberId, String orderSn, String productName, String amount, String paymentDate) {

        Map<String, Object> data = new HashMap<>();

        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", orderSn);
        data.put("keyword1", value1);

        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", productName);
        data.put("keyword2", value2);


        Map<String, Object> value3 = new HashMap<>();
        value3.put("value", amount);
        data.put("keyword3", value3);

        Map<String, Object> value4 = new HashMap<>();
        value4.put("value", paymentDate);
        data.put("keyword4", value4);

        hanldeToSendNotice(CREATE_ORDER_TEMPLATE_ID, data, memberId);
    }

    @Override
    public void sendDeliveryOrderNotice(Long memberId, String companyName, String trackingNumber, String orderSn, String receiver, String receiveAddress, String deliveryDate) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", companyName);
        data.put("keyword1", value1);
        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", trackingNumber);
        data.put("keyword2", value2);

        Map<String, Object> value3 = new HashMap<>();
        value3.put("value", orderSn);
        data.put("keyword3", value3);

        Map<String, Object> value4 = new HashMap<>();
        value4.put("value", receiver);
        data.put("keyword4", value4);

        Map<String, Object> value5 = new HashMap<>();
        value5.put("value", receiveAddress);
        data.put("keyword5", value5);

        Map<String, Object> value6 = new HashMap<>();
        value6.put("value", deliveryDate);
        data.put("keyword6", value6);
        hanldeToSendNotice(DELIVERY_ORDER_TEMPLATE_ID, data, memberId);
    }

    @Override
    public void incomeNotice(Long memberId, String incomeAmount, String incomeDate, Long formMemberId) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", incomeAmount);
        data.put("keyword1", value1);

        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", incomeDate);
        data.put("keyword2", value2);

        Map<String, Object> value3 = new HashMap<>();
        UmsMember fromMember = memberService.getById(formMemberId);
        String nickName = "";
        try {
            nickName = URLDecoder.decode(fromMember.getNickname(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        value3.put("value", nickName);
        data.put("keyword3", value3);
        hanldeToSendNotice(INCOME_TEMPLATE_ID, data, memberId);
    }

    @Override
    public void approvalNotice(Long memberId, String nickName, String type, String status, String approvalDate) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", nickName);
        data.put("keyword1", value1);

        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", type);
        data.put("keyword2", value2);

        Map<String, Object> value3 = new HashMap<>();
        value3.put("value", status);
        data.put("keyword3", value3);


        Map<String, Object> value4 = new HashMap<>();
        value4.put("value", approvalDate);
        data.put("keyword4", value4);

        hanldeToSendNotice(APPROVAL_TEMPLATE_ID, data, memberId);
    }

    @Override
    public void withdrawNotice(Long memberId, String amount, String applyDate) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", amount);
        data.put("keyword1", value1);


        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", applyDate);
        data.put("keyword2", value2);

        hanldeToSendNotice(WITHDRAW_TEMPATE_ID, data, memberId);
    }

    @Override
    public void transferFailNotice(String amount, String type, String reason, String transferDate) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", amount);
        data.put("keyword1", value1);

        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", type);
        data.put("keyword2", value2);

        Map<String, Object> value3 = new HashMap<>();
        value3.put("value", reason);
        data.put("keyword3", value3);


        Map<String, Object> value4 = new HashMap<>();
        value4.put("value", transferDate);
        data.put("keyword4", value4);

        hanldeToSendNotice(TRANSFER_FAILE_TEMPLATE_ID, data);
    }

    @Override
    public void sendGroupPurchaseSuccess(Long memberId, String productName, Integer groupCount, String owner, BigDecimal price, BigDecimal groupPrice, String associates) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", productName);
        data.put("keyword1", value1);

        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", groupCount);
        data.put("keyword2", value2);

        Map<String, Object> value3 = new HashMap<>();
        value3.put("value", owner);
        data.put("keyword3", value3);


        Map<String, Object> value4 = new HashMap<>();
        value4.put("value", price.toString());
        data.put("keyword4", value4);

        Map<String, Object> value5 = new HashMap<>();
        value5.put("value", groupPrice.toString());
        data.put("keyword5", value5);

        Map<String, Object> value6 = new HashMap<>();
        value6.put("value", associates);
        data.put("keyword6", value6);

        hanldeToSendNotice(GROUP_PURCHASE_TEMPLATE_ID, data, memberId);
    }

    @Override
    public void sendBargainInprogessNotice(Long memberId, String productName, String inprogessDesc, String bargainPrice, String minPrice, String endTime, String tipMsg) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", productName);
        data.put("keyword1", value1);

        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", inprogessDesc);
        data.put("keyword2", value2);

        Map<String, Object> value3 = new HashMap<>();
        value3.put("value", bargainPrice);
        data.put("keyword3", value3);


        Map<String, Object> value4 = new HashMap<>();
        value4.put("value", minPrice);
        data.put("keyword4", value4);

        Map<String, Object> value5 = new HashMap<>();
        value5.put("value", endTime);
        data.put("keyword5", value5);

        Map<String, Object> value6 = new HashMap<>();
        value6.put("value", tipMsg);
        data.put("keyword6", value6);

        hanldeToSendNotice(BARGAIN_INPROGESS_TEMPLATE_ID, data, memberId);
    }

    @Override
    public void sendGroupPurchaseFaild(Long memberId, String productName, String startTime,  BigDecimal groupPrice,
                                       Integer groupCount, String reason, String orderSn, String tipMsg) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value1 = new HashMap<>();
        value1.put("value", productName);
        data.put("keyword1", value1);

        Map<String, Object> value2 = new HashMap<>();
        value2.put("value", startTime);
        data.put("keyword2", value2);

        Map<String, Object> value3 = new HashMap<>();
        value3.put("value", groupPrice.toString());
        data.put("keyword3", value3);

        Map<String, Object> value4 = new HashMap<>();
        value4.put("value", groupCount);
        data.put("keyword4", value4);

        Map<String, Object> value5 = new HashMap<>();
        value5.put("value", reason);
        data.put("keyword5", value5);

        Map<String, Object> value6 = new HashMap<>();
        value6.put("value", orderSn);
        data.put("keyword6", value6);

        Map<String, Object> value7 = new HashMap<>();
        value7.put("value", tipMsg);
        data.put("keyword7", value7);

        hanldeToSendNotice(GROUP_PURCHASE_FAIL_TEMPLATE_ID, data, memberId);
    }


    private int generate4Code()
    {
        return (int)((Math.random()*9+1)*1000);
    }

    private void hanldeToSendNotice(String templateId, Map<String, Object> keywords)
    {
        hanldeToSendNotice(templateId, keywords, null);
    }
    private void hanldeToSendNotice(String templateId, Map<String, Object> keywords, Long memberId)
    {
        UmsMember member;
        if(null == memberId) {
            member = memberService.getCurrentMember();
        }
        else
        {
            member =  memberService.getById(memberId);
        }
        UmsMemberForm memberForm = memberFormService.getFormIdByMember(member.getId());
        if(null == memberForm )
        {
            return;
        }
        WeappTemplate weappTemplate = WeappTemplate.builder()
                .template_id(templateId)
                .form_id(memberForm.getFormId())
                .page("pages/index/index")
                .data(keywords)
                .build();

        WxsmallTemplate template = WxsmallTemplate.builder()
                .touser(member.getWxOpenId())
                .weapp_template_msg(weappTemplate).build();

        weChatConnector.sendMsg(template);
        memberFormService.delFormById(memberForm.getId());
    }


}
